<template>
<div>

    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <Son :obj="obj"></Son>

    <!-- 卡片表格区域 -->
    <el-card>
        <!-- 搜索与添加区域 -->
        <el-row :gutter="20">
            <el-col :span="8">
                <el-input placeholder="请输入内容" clearable v-model="userParam.query" @clear="getUserlist" @keyup.enter.native="getUserlist">
                    <el-button slot="append" icon="el-icon-search" @click="getUserlist"></el-button>
                </el-input>
            </el-col>
            <el-col :span="4">
                <el-button type="primary" @click="dialogVisible = true">添加</el-button>
            </el-col>
        </el-row>
        <!-- 用户列表区域 -->
        <el-table :data="userList" border stripe size="medium">
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="username" label="姓名"></el-table-column>
            <el-table-column prop="email" label="邮箱"></el-table-column>
            <el-table-column prop="mobile" label="电话"> </el-table-column>
            <el-table-column prop="role_name" label="角色"> </el-table-column>
            <el-table-column label="状态">
                <template slot-scope="scope">
                    <!-- {{scope.row}} -->
                    <el-switch v-model="scope.row.mg_state" active-color="#13ce66" inactive-color="#ff4949" @change="switchClick(scope.row)">
                    </el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="180px">
                <template slot-scope="scope">
                    <!-- 编辑按钮 -->
                    <el-button type="primary" icon="el-icon-edit" size="mini" @click="editClick(scope.row.id)">
                    </el-button>
                    <!-- 删除按钮 -->
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserClick(scope.row.id)">
                    </el-button>
                    <!-- 分配角色按钮 -->
                    <el-tooltip effect="dark" content="分配角色按钮" placement="top-start" :enterable="false">
                        <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
                    </el-tooltip>
                </template>
            </el-table-column>
        </el-table>
        <!-- 底部分页 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="userParam.pagenum" :page-sizes="[3, 5, 7, 10]" :page-size="userParam.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>

        <!-- 添加用户Dialog对话框 -->
        <el-dialog title="添加用户" :visible.sync="dialogVisible" @close="addDialogClose" width="50%">
            <el-form :model="adduserForm" :rules="adduserRules" ref="adduserRef" label-width="100px" class="demo-ruleForm">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="adduserForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="adduserForm.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="adduserForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="adduserForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="info" @click="adduserReset">重 置</el-button>
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="userformSubmit">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 修改用户Dialog对话框 -->
        <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
            <el-form :model="editForm" :rules="edituserRules" ref="edituserRef" label-width="80px">
                <el-form-item label="用户名">
                    <el-input disabled v-model="editForm.username"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="editForm.mobile"></el-input>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editSubmit">确 定</el-button>
            </span>
        </el-dialog>
    </el-card>
</div>
</template>

<script>
// 引入axiso
import axios from 'axios'
import Son from './son.vue'

import {
    usersApi,
    userStateApi,
    adduserSubmitApi,
    inquireuserApi,
    edituserApi,
    removeuserApi,
} from '../../request/api'
export default {
    data() {
        //验证邮箱的规则
        var checkEmail = (rule, value, callback) => {
            // // 验证邮箱的正则表达式
            const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
            if (regEmail.test(value)) {
                // 合法的邮箱
                return callback()
            }

            callback(new Error('请输入合法的邮箱'))
        }
        //验证手机号的规则
        var checkMoblie = (rule, value, callback) => {
            // 验证手机号的正则表达式
            const regMobile =
                /^(0|86|17951)?(13[0-9]|15[12356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
            if (regMoblie.test(value)) {
                // 合法的手机号
                return callback()
            }
            callback(new Error(' 请输入合法的手机号'))
        }
        return {
            obj: {
                a: 1,
                b: 2
            },
            userList: [],
            // 获取用户列表参数
            userParam: {
                query: '',
                pagenum: 1,
                pagesize: 2,
            },
            total: 0,
            switchValue: false,
            switchState: false,
            dialogVisible: false, //添加用户对话框隐藏布尔值
            //添加用户modle数据
            adduserForm: {
                username: '',
                password: '',
                email: '',
                mobile: '',
            },
            //添加用户表单验证规则
            adduserRules: {
                username: [{
                        required: true,
                        message: '请输入用户名',
                        trigger: 'blur'
                    },
                    {
                        min: 3,
                        max: 10,
                        message: '长度在 3 到 10 个字符',
                        trigger: 'blur',
                    },
                ],
                password: [{
                        required: true,
                        message: '请输入密码',
                        trigger: 'blur'
                    },
                    {
                        min: 6,
                        max: 16,
                        message: '长度在 6 到 16 个字符',
                        trigger: 'blur',
                    },
                ],
                email: [{
                        required: true,
                        message: '请输入邮箱',
                        trigger: 'blur'
                    }, //第一个是为了验证用户有没有输入邮箱
                    {
                        validator: checkEmail,
                        trigger: 'blur'
                    }, //第二个是为了验证用户输入的邮箱规则是否合法
                ],
                mobile: [{
                        required: true,
                        message: '请输入手机号',
                        trigger: 'blur'
                    },
                    {
                        min: 11,
                        message: '请输入合法手机号',
                        trigger: 'blur'
                    },
                ],
            },
            editDialogVisible: false, //编辑用户对话框隐藏布尔值
            editForm: {}, //查询到的用户信息对象
            // 修改用户信息的验证规则
            edituserRules: {
                email: [{
                        required: true,
                        message: '请输入邮箱',
                        trigger: 'blur'
                    }, //第一个是为了验证用户有没有输入邮箱
                    {
                        validator: checkEmail,
                        trigger: 'blur'
                    }, //第二个是为了验证用户输入的邮箱规则是否合法
                ],
                mobile: [{
                        required: true,
                        message: '请输入手机号',
                        trigger: 'blur'
                    },
                    {
                        min: 11,
                        message: '请输入合法手机号',
                        trigger: 'blur'
                    },
                ],
            },
        }
    },
    components: {
        Son
    },
    created() {
        this.getUserlist()
    },
    methods: {
        //获取用户列表数据
        getUserlist() {
            usersApi(this.userParam).then((res) => {
                this.userList = res.data.data.users
                this.total = res.data.data.total
                console.log('this is')
            })
        },
        // 监听pagesize 显示多少条 改变的事件
        handleSizeChange(newSize) {
            this.userParam.pagesize = newSize
            this.getUserlist()
        },
        // 监听用户列表页码值 （第几页）的事件
        handleCurrentChange(newPage) {
            this.userParam.pagenum = newPage
            this.getUserlist()
        },
        // 监听用户列表的状态按钮事件
        switchClick(switchParam) {
            console.log(switchParam)
            userStateApi(switchParam.id, switchParam.mg_state).then((res) => {
                if (res.data.meta.status != 200) {
                    switchParam.mg_state = !switchParam.mg_state
                    return this.$message.error(res.data.data.meta.msg)
                }
                this.$message.success(res.data.meta.msg)
            })
        },
        //监听用户列表修改按钮事件,查询用户信息
        editClick(ids) {
            inquireuserApi(ids).then((res) => {
                console.log(res)
                if (res.data.meta.status != 200) {
                    return this.$message.error('查询用户信息失败')
                }
                this.editForm = res.data.data
                this.editDialogVisible = true
            })
        },
        //监听添加用户的重置按钮  清空输入框
        adduserReset() {
            this.$refs.adduserRef.resetFields()
        },
        //监听添加用户对话框的关闭/取消按钮
        addDialogClose() {
            this.$refs.adduserRef.resetFields()
        },
        // 监听添加用户对话框确定按钮
        userformSubmit() {
            this.$refs.adduserRef.validate((valid) => {
                // valid为布尔值，为true时则验证通过，为false则未通过
                console.log(this.adduserForm)
                adduserSubmitApi(this.adduserForm).then((res) => {
                    console.log(res)
                    if (res.data.meta.status != 201) {
                        return this.$message.error('添加用户失败')
                    }
                    // 隐藏对话框
                    this.dialogVisible = false
                    this.getUserlist()
                    this.$message.success('添加用户成功')
                })
            })
        },
        //监听修改对话框关闭按钮事件
        editDialogClosed() {
            console.log('ddd')
            this.$refs.edituserRef.resetFields()
        },
        //监听修改对话框确定按钮
        editSubmit() {
            let editParams = {
                email: this.editForm.email,
                mobile: this.editForm.mobile,
            }
            this.$refs.edituserRef.validate((valid) => {
                edituserApi(this.editForm.id, editParams).then((res) => {
                    console.log(res.data)
                    if (res.data.meta.status !== 200) {
                        return this.$message.error('更新用户信息失败')
                    }
                    // 则：关闭对话框
                    this.editDialogVisible = false
                    //刷新用户数据列表
                    this.getUserlist()
                    //提示修改成功
                    this.$message.success('更新用户信息成功')
                })
            })
        },
        //监听删除按钮事件
        removeUserClick(id) {
            console.log(id)

            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                })
                .then(() => {
                    //点击确定的回调
                    removeuserApi(id).then(({
                        data: res
                    }) => {
                        console.log(res)
                        if (res.meta.status !== 200) {
                            return this.$message({
                                type: 'error',
                                message: res.meta.msg,
                            })
                        }
                        this.getUserlist()
                        this.$message({
                            type: 'success',
                            message: '删除成功!',
                        })
                    })
                })
                .catch(() => {
                    //点击取消的回调
                    this.$message({
                        type: 'info',
                        message: '已取消删除',
                    })
                })
        },
    },
}
</script>

<style lang="scss">
.el-breadcrumb {
    margin-bottom: 15px;
    font-size: 12px;
}

.el-table {
    margin-top: 15px;
    font-size: 12px;
}

.el-pagination {
    margin-top: 15px;
}
</style>
